package com.zxt.mq.mvc.log.receive;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxt.mq.config.rabbitmq.RabbitData;
import com.zxt.mq.mvc.log.receive.zconstant.ReceiveLogConstant;
import com.zxt.mq.mvc.log.receive.zdomain.MessageReceiveLog;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 接收消息记录 服务实现类
 * </p>
 *
 * @author zxt
 * @since 2022-07-25
 */
@Service
public class MessageReceiveLogServiceImpl extends ServiceImpl<MessageReceiveLogMapper, MessageReceiveLog> implements MessageReceiveLogService {
    @Value("${spring.rabbitmq.message-log.log}")
    private boolean log;

    @Override
    public void saveLog(RabbitData rabbitData, String status) {
        if (log) {
            if (ObjectUtil.isNotNull(rabbitData)) {
                MessageReceiveLog messageLog = getByUri(rabbitData.getUri());
                if (ObjectUtil.isNull(messageLog)) {
                    messageLog = new MessageReceiveLog();
                }
                messageLog.setReceiveMsg(rabbitData.getSendMsg())
                          .setReceiveTime(LocalDateTime.now())
                          .setStatus(status)
                          .setUri(rabbitData.getUri());
                saveOrUpdate(messageLog);
            }
        }
    }

    @Override
    public MessageReceiveLog getByUri(String uri) {
        if (StrUtil.isEmpty(uri)) {
            return null;
        }
        return getOne(new QueryWrapper<MessageReceiveLog>().eq(MessageReceiveLog.DbKey.uri, uri));
    }

    @Override
    public List<String> listFailUri() {
        List<MessageReceiveLog> list = list(new QueryWrapper<MessageReceiveLog>().eq(MessageReceiveLog.DbKey.status,
                                                                                     ReceiveLogConstant.UN_CONFIRM));
        return CollUtil.isEmpty(list) ?
               new ArrayList<>() :
               list.stream().map(MessageReceiveLog::getUri).collect(Collectors.toList());
    }
}
